﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;
using System.ComponentModel;
using System.Xml.Serialization;
using System.Net;

namespace Rdz.Xml
{
	[Serializable()]
	public abstract class CommonXmlSerializer
	{
		#region "Common Functions"
		public CommonXmlSerializer DeserializeFromFile(string path)
		{
			return Deserialize(File.ReadAllText(path));
		}

		public CommonXmlSerializer DeserializeFromUrl(string address)
		{
			var wc = new WebClient();
			wc.UseDefaultCredentials = true;
			return Deserialize(wc.DownloadString(address));
		}

		public CommonXmlSerializer Deserialize(string InputText)
		{
			CommonXmlSerializer cxs;
			XmlSerializer xSz = new XmlSerializer(this.GetType());
			using (var ms = new MemoryStream())
			{
				byte[] InputByte = ASCIIEncoding.ASCII.GetBytes(InputText);
				ms.Write(InputByte, 0, InputByte.Length);
				ms.Position = 0;
				cxs = (CommonXmlSerializer)xSz.Deserialize(ms);
			}
			return cxs;
		}

		public string Serialize()
		{
			string sRet = "";
			XmlSerializer xSz = new XmlSerializer(this.GetType());
			using (var ms = new MemoryStream())
			{
				xSz.Serialize(ms, this);
				ms.Position = 0;
				using (var sr = new StreamReader(ms))
				{
					sRet = sr.ReadToEnd();
				}
			}
			return sRet;
		}

		#endregion
	}
}

